package com.hub.videobrowsdownload

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.format.Formatter
import android.util.Log
import android.webkit.WebView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.FileProvider
import coil.compose.AsyncImage
import com.forest.download.State
import java.io.File
import java.net.URLConnection


/**
 * https://github.com/jhy/jsoup?tab=readme-ov-file
 */
class BrowsTestMainActivity : ComponentActivity() {
    val tabWebViewModel: BrowsTabWebViewModel by viewModels()

    var countDownTimer: CountDownTimer? = null
    var isTimerStart = false
    var webView: WebView? = null

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val initUrl = tabWebViewModel.currentWebUrl.value!!
        setContent {
            Column {
                BoxWebView(initUrl)


                VideoLis()
            }
        }
    }

    @Composable
    private fun VideoLis() {
        val videoList = tabWebViewModel.findVideoList.observeAsState()
        if (!videoList.value.isNullOrEmpty()) {
            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(10.dp)
                    .background(Color.Magenta)
            )
            LazyColumn(
                Modifier.height(300.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                items(videoList.value ?: arrayListOf()) {
                    ItemLazy(it)
                }
            }
        }
    }

    @Composable
    private fun ItemLazy(it: BrowsVideoPrepare) {
        val context = LocalContext.current
        val isLoading = it.stateLiveData.observeAsState()
        val thumbPath = it.thumbPath.observeAsState()
        val width = it.videoWidth.observeAsState()
        val height = it.videoHeight.observeAsState()
        val duration = it.videoDuration.observeAsState()
        val fileSize = it.videoLength.observeAsState()
        val isM3U8 = it.isM3U8

        val entity = it.downloadWrapper.observeAsState()

        Box(
            Modifier
                .fillMaxWidth()
                .height(100.dp)
                .background(Color.White)
                .clickable(interactionSource = remember {
                    MutableInteractionSource()
                }, indication = rememberRipple()) {
                    if (entity.value?.state is State.Succeed) {
                        val f = entity.value?.task?.file()
                        if (f != null) {
                            shareFile(context,f)
                        }

                    } else {
                        Toast
                            .makeText(context, "开始下载", Toast.LENGTH_SHORT)
                            .show()
                        BrowsApplication.browsMyViewModel.startDownload(context, it)
                    }
                }
        ) {
            Row(Modifier.fillMaxSize()) {
                AsyncImage(
                    model = thumbPath.value,
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxHeight()
                        .aspectRatio(1f),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Column(Modifier.align(Alignment.CenterVertically)) {

                    Text(
                        text = it.getPath(), fontSize = 15.sp, color = Color.Black
                    )
                    val d =
                        if (isM3U8) (duration.value ?: 0.0) else ((duration.value ?: 0.0) / 1000)
                    val minutes = d / 60
                    val seconds = d % 60
                    Text(
                        text = String.format(
                            "%02d:%02d" + " " + Formatter.formatFileSize(
                                context,
                                fileSize.value ?: 0L
                            ) + " ${width.value}X${height.value}", minutes.toInt(), seconds.toInt()
                        ),
                        fontSize = 12.sp,
                        color = Color.Black
                    )
                    if (entity.value != null) {
                        var message = ""
                        var mage = ""
                        val state = entity.value!!.state
                        Log.i(
                            "DOWNLOAD_MODEL",
                            "获取到新的信息: ${state?.progress?.percentStr()} ${state?.progress?.downloadSize}/${state?.progress?.totalSize}"
                        )

                        mage =
                            "${(state?.progress?.percentStr())} ${state?.progress?.downloadSize}/${state?.progress?.totalSize}"
                        when (entity.value!!.state) {
                            is State.None -> { // text.value = "下载"

                                message = "State.None"
                            }

                            is State.Waiting -> {
                                //    text.value = "等待中"
                                message = "等待中"
                            }

                            is State.Downloading -> {
                                // text.value = state.progress.percentStr()
                                // 更新进度
                                // progress.value = state.progress.progress()

                                message = "Downloading"
                            }

                            is State.Failed -> { // text.value = "重试"
                            }

                            is State.Stopped -> {// text.value = "继续"
                            }

                            is State.Succeed -> {// text.value = "完成"
                                message =
                                    "Download Success: 下载完成，点我分享视频"
                            }

                            else -> {}
                        }
                        Text(
                            text = message, fontSize = 12.sp,
                            color = Color.Black
                        )
                        Text(
                            text = mage, fontSize = 12.sp,
                            color = Color.Black
                        )
                    }
                }
            }

            if (isLoading.value == 1) {
                CircularProgressIndicator(Modifier.align(Alignment.Center))
            }
        }
    }

    @Composable
    private fun ColumnScope.BoxWebView(url: String) {
        Log.i("加载网页1", url)
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            BrowsMyWebView(tabWebViewModel) { webView ->
                if (!webView.url.isNullOrEmpty()) {
                    return@BrowsMyWebView
                }
                Log.i("加载网页2", url)
                this@BrowsTestMainActivity.webView = webView
                webView.loadUrl(url)

                countDownTimer?.cancel()
                countDownTimer = object : CountDownTimer(0x3B9AC9FFL, 7000L) {

                    // android.os.CountDownTimer
                    override fun onFinish() {}

                    // android.os.CountDownTimer
                    override fun onTick(v: Long) {

                        BrowsM3U8Helper.tickShowHtmlVideo(webView)
                    }
                }
                countDownTimer?.start()
                isTimerStart = true
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (isTimerStart) {
            isTimerStart = false
            countDownTimer?.cancel()
        }
    }

    override fun onResume() {
        super.onResume()
        if (!isTimerStart) {
            isTimerStart = true
            countDownTimer?.start()
        }
    }

    override fun onBackPressed() {
        if (f()) {

        } else {
            super.onBackPressed()
        }
    }


    fun f(): Boolean {
        if (this.webView?.canGoBack() == true) {
            Log.d("canGoBack", "goBack: " + this.webView?.getUrl())
            this.webView?.goBack()
            return true
        }
        this.webView?.loadUrl("about:blank")
        return false
    }
    fun shareFile(context: Context, file: File) {
        try {
            val uri = FileProvider.getUriForFile(context, context.packageName, file)

            val intent = Intent(Intent.ACTION_SEND)
            var MIME_TYPE: String? = null
            MIME_TYPE = try {
                URLConnection.guessContentTypeFromName(file.name)
            } catch (e: java.lang.Exception) {
                "*/*"
            }
            intent.type = MIME_TYPE
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

            context.startActivity(Intent.createChooser(intent, "Share"))
        } catch (e: Exception) {
        }
    }

}